package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.feign.client.ArticleFeignClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private ArticleFeignClient articleFeignClient;

    @Autowired
    private WmNewsTaskService taskService;

    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //0.检查文章
        dto.checkParam();
        //1.检查是否登录
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.分页条件查询
        IPage iPage = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();

        //状态精确查询
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //频道精确查询
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //时间范围查询
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }
        //关键字模糊查询
        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //查询当前登录用户的文章
        queryWrapper.eq(WmNews::getUserId, user.getId());
        //按照发布时间倒序排序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        iPage = page(iPage, queryWrapper);
        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal());
        responseResult.setData(iPage.getRecords());

        return responseResult;
    }

    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        //1.参数判断
        //判断content文章内容不能为空
        if (dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或者修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //封面图片
        String images = StringUtils.join(dto.getImages(), ".");
        if (images != null) {
            wmNews.setImages(images);
        }
        if (dto.getType() == -1) {
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);
        //如果是草稿
        if (dto.getStatus() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CAO_GAO);
        }

        //2.5抽取出内容中的图片地址信息
        List<String> contentImageList = chouquContentImage(wmNews);
        //3.文章与内容的关联
        saveWmNewsContentImage(wmNews, contentImageList, (short) 0);

        //4.文章与封面图片关联
        saveWmNewsFengmianImage(wmNews, dto, contentImageList, (short) 1);
        //自动审核
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        taskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 第四个抽取方法，文章与封面图片的关联关系
     * 如果是自动的话，从内容图片中去提取作为封面图片
     * 规则：
     * 如果内容中的图片大于等于1小于3的话，则提取第一个作为封面图片，则是单图
     * 如果内容中的图片个数大于等于3时，则提取前三张图片作为封面图片，则是多图
     * 如果内容中的图片个数为0，则认为是无图
     *
     * @param wmNews
     * @param dto
     * @param contentImageList
     */
    private void saveWmNewsFengmianImage(WmNews wmNews, WmNewsDto dto, List<String> contentImageList, short type) {
        //    1.获取封面图片地址
        List<String> images = dto.getImages();
        //    如果是单图，三图，或者无图，则正常执行
        short newsType = 0;
        //    如果是自动
        if (dto.getType() == -1) {
            //    从内容中取出图片的操作
            if (contentImageList.size() >= 1 && contentImageList.size() < 3) {
                //    单图，则取出第一张作为封面图片
                images = contentImageList.stream().limit(1).collect(Collectors.toList());
                newsType = 1;
            } else if (contentImageList.size() >= 3) {
                //    多图，取出前三张作为封面图片
                images = contentImageList.stream().limit(3).collect(Collectors.toList());
                newsType = 3;
            } else {
                //    无图
                newsType = 0;
            }
            //    最后要更新wm_news表的文章布局
            wmNews.setImages(StringUtils.join(images, ","));
            wmNews.setType(newsType);
            updateById(wmNews);
        }
        //    最终也要执行中间表的新增
        saveWmNewsMaterial(wmNews, images, type);
    }

    /**
     * 第三个抽取方法
     *
     * @param
     * @return
     */
    private void saveWmNewsContentImage(WmNews wmNews, List<String> contentImageList, Short type) {
        saveWmNewsMaterial(wmNews, contentImageList, type);
    }

    /**
     * 第五个抽取方法，专门用来新增中间表
     *
     * @param
     * @param type
     */
    private void saveWmNewsMaterial(WmNews wmNews, List<String> imageList, Short type) {
        if (imageList != null && imageList.size() > 0) {

            //2.2根据图片地址集合去查询wm_material表中对应的id
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageList));
            //2.3获取对应的素材id集合
            List<Integer> contentImageIdList = wmMaterials.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());
            //    1.批量新增wm_news_material表
            wmNewsMaterialMapper.saveRelations(contentImageIdList, wmNews.getId(), type);
        }

    }

    /**
     * 第二个抽取方法，从内容中抽取出图片地址的集合
     *
     * @param
     */
    private List chouquContentImage(WmNews wmNews) {
        List<String> contentImageList = new ArrayList<>();

        //    1.获取文章内容
        String content = wmNews.getContent();
        //    2.从内容中抽取图片集合
        //    2.1转换类型
        List<Map> contentList = JSON.parseArray(content, Map.class);
        //    2.2遍历集合
        for (Map map : contentList) {
            if (map.get("type").equals("image")) {
                String path = (String) map.get("value");
                contentImageList.add(path);
            }
        }
        return contentImageList;
    }

    /**
     * 抽取的第一个方法，保存或者修改wm_news表
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //封装数据用户id
        wmNews.setUserId((WmThreadLocalUtil.getUser().getId()));
        //创建时间
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        //新增
        if (wmNews.getId() == null) {
            //    新增文章
            save(wmNews);
        } else {
            //    先删除文章素材中间表
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //    修改文章
            updateById(wmNews);
        }
    }

    /*
    根据文章ID，查询文章图文信息
     */
    @Override
    public ResponseResult getOne(Integer id) {
        //获取图文信息
        WmNews news = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));
        //如果图文信息为空
        if (news == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //如果不为空
        ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, "操作成功");
        responseResult.setData(news);
        return responseResult;
    }

    /**
     * 文章删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del_news(Integer id) {
        //如果id为空,则判断不能进行查询图文信息
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章id不可缺少");
        }
        //查询图文信息
        WmNews news = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));
        //如果图文信息不存在
        if (news == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //如果图文信息已发布，则不能删除
        if (news.getStatus() == 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章已发布，不能删除");
        }
        //删除图文信息及其引用素材信息
        remove(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, "操作成功");
    }

    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult down_or_up(WmNewsDto dto) {
        //1.前台传来的ID不能为空
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章id不可缺少");
        }
        //2.查询传来的ID查询图文信息
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()));

        //3.查询文章不存在
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //4.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_ADMIND);
        }
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);


        //5，发送消息，通知article端修改文章配置
        if(wmNews.getArticleId()!=null){
            Map<String,Object> map=new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",dto.getEnable());
            kafkaTemplate.send("wm_topic",JSON.toJSONString(map));
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, "操作成功");
    }
}
